import { tip, util } from '@/utils'
import { storage } from '@/utils'

const request = (config:any) => {
	return new Promise((resolve, reject) => {
		
		const domain = import.meta.env.VITE_APP_DOMAIN
		const baseApi = import.meta.env.VITE_APP_BASE_API
		const params = config.params?util.paramsStr(config.params):""
		const url = domain + baseApi + config.url + params
		const token = storage.getLocalStorage('token')
		const conentType = config.contentType || 'application/json;charset=utf-8'
		
		if(!config.noLoading){
			tip.showLoading('加载中...')
		} 
		
		uni.request({
		    url: url,
		    method:config.method,
			data: config.data,
			sslVerify: false,
		    header: {
				'Content-type': conentType,
				'Authorization': 'Bearer ' + token
		    },
		    success: (res: any) => {
				const code = res.data.code
				if(code === 200) {
					resolve(res.data)
				} else {
					if(code === 401) {
						if(config.noJump && config.url === '/mall/shoppingCart/shoppingCartList') {
							return reject(res.data.msg)
						} else {
							uni.reLaunch({
								url:'/pages/auth/login'
							})
						}
						
						// if(showModal) {
						// 	showModal = false
						// 	uni.showModal({
						// 		title:'温馨提示',
						// 		content:'登录状态已过期，请重新登录!',
						// 		confirmColor:'#1769ff',
						// 		confirmText:'重新登录',
						// 		cancelText:'返回',
						// 		success:(res:any) => {
						// 			if(res.confirm) {
						// 				uni.redirectTo({
						// 					url:'/pages/auth/login'
						// 				})
						// 			}
						// 		},
						// 		complete:() => {
						// 			showModal = true
						// 		}
						// 	})
						// }
					} else if(code === 403) {
						tip.showToast('当前操作没有权限!')
						uni.redirectTo({
							url:'/pages/auth/login'
						})
					} else if(code === 500) {
						tip.showToast('系统未知错误!')
					} else if(code === 502) {
						tip.showToast(res.data.msg)
					} else {
						tip.showToast('未知错误！')
					}
					reject(res.data.msg)
				}
		    },
			fail:(error) => {
				reject(error)
			},
			complete: () => {
				tip.hideLoading()
				
			}
		})
	})
}

export default request
